package pacote.doandroid;


import java.awt.PageAttributes.MediaType;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.core.UriBuilder;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.WebResource.Builder;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;



public class Utils {
	
//	static String  pacoteParaArquivosBackup = "/home/airton/workspace/p2pWS/arquivosParaBackup/";
	
	public static URI getBaseURI() {
		return UriBuilder.fromUri("http://localhost:8080/p2pWS").build();
		
	}


	public static ClientResponse saveData(String file)
			throws FileNotFoundException {
		WebResource content = Client.create().resource(getBaseURI());
		
		ClientResponse clientResponse = null;

		int length = (int) file.length();
		FileInputStream fis = new FileInputStream(file);
		
		
		Builder type = content.path("/backup/save/nomearquivo?l=" + length).type(
				javax.ws.rs.core.MediaType.TEXT_HTML_TYPE );
		
		clientResponse = type.put(ClientResponse.class,fis);
		
		System.out.println(clientResponse);
		return clientResponse;
	}

	
	public static  List<String> listFiles() {
		List<String> list = new ArrayList<String>();
		list.add("item");
		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource service = client.resource(Utils.getBaseURI());

		ClientResponse response= null;
		
		try {
			response = service.path("/backup/maq100/maq100/")
					.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(ClientResponse.class);
		} catch (Exception e) {
			list.add("item2");
			return list;
		}

		if (response == null) {
			return list;
		}
		
		String msgError = ErrorsEnum.contains(response.toString());
		
		if(msgError != null){
			list.add(msgError);
		}
		
		//Falta tratar quando der certo o retorno dos arquivos.
		
		return list;
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		ClientResponse saveData = saveData("/home/airton/workspace/ClientAndroid/AndroidManifest.xml");
		System.out.println(saveData.getStatus());
	}
	
}
